

#import "PUXuanCaiVC.h"
#import "PUCityListModel.h"
#import "PUXuanCaiCell.h"
#import "PUModel.h"
#import "PURecordVC.h"
#import "PUXuanCaiDetailsVC.h"
#import "PUData.h"

@interface PUXuanCaiVC ()<UITableViewDelegate,UITableViewDataSource,FLSeeFlowersCellDelegate>

@property (nonatomic,retain)UITableView *tableView;
@property (nonatomic,retain)NSMutableArray *dizhiData;
@property (nonatomic,retain)NSMutableArray *dizhiData2;
@property (nonatomic,retain)NSMutableArray *data;
@property (nonatomic)int page;
@property (nonatomic) NSInteger last_id;
@property (nonatomic)int isFirstLoad;
@property (nonatomic)NSInteger dataCount;
@end

@implementation PUXuanCaiVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor=[UIColor clearColor];
    self.data=[NSMutableArray array];
    self.dizhiData=[NSMutableArray array];
    self.dizhiData2=[NSMutableArray array];
    
    
    _tableView = [[UITableView alloc] init];
    _tableView.backgroundColor=[UIColor clearColor];
    //解决scrollToRowAtIndexPath：滚动位置偏差问题
    _tableView.estimatedRowHeight = 0;
    _tableView.estimatedSectionFooterHeight = 0;
    _tableView.estimatedSectionHeaderHeight = 0;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;//设置分隔线样式
    _tableView.bounces = YES;
    _tableView.delegate=self;
    _tableView.dataSource=self;
    [self.view addSubview:self.tableView];
    self.edgesForExtendedLayout = UIRectEdgeTop;
//    _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;


    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset = 0;
    }];
    
    self.tableView.emptyDataSetSource = self.tableView;
    self.tableView.emptyDataSetDelegate= self.tableView;
    __weak typeof(self) weakSelf = self;
    
//    NSDictionary *saveSystemConfig = [Config getOpenAppConfig];
//    if (saveSystemConfig!=nil) {
//        int is_examine=[saveSystemConfig[@"is_examine"] intValue];
//        if (is_examine==1) {
//            [self loadData];
//        }else{
//            self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//                [weakSelf loadData];
//            }];
//            self.tableView.mj_footer.ignoredScrollViewContentInsetBottom = iPhoneXs ? 34 : 0;
//            [self.tableView.mj_header beginRefreshing];
//        }
//    }else{
//        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//            [weakSelf loadData];
//        }];
//        self.tableView.mj_footer.ignoredScrollViewContentInsetBottom = iPhoneXs ? 34 : 0;
//        [self.tableView.mj_header beginRefreshing];
//    }
   
    [self loadData];
    self.tableView.mj_footer=[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadMore_get_they_info];
    }];
    
   
    
    self.tableView.mj_footer.hidden = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updataData) name:@"loginSuccessUpdataNotification" object:nil];//登录成功---刷新列表
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(scroVC) name:@"showLoginNotification" object:nil];//退出登录成功，列表有数据时滚动到第一个
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(daShanSuccess:) name:@"chatAccostSuccessNotification" object:nil];//搭讪成功
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(behaviorBlackSuccess:) name:@"CPBehaviorBlackNotification" object:nil];//用户详情页拉黑
   
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(is_praiseSuccess:) name:@"is_praiseNotification" object:nil];//详情页赞
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(behaviorBlackSuccess:) name:@"CPBehaviorBlackNotification" object:nil];//用户详情页拉黑
}
-(void)behaviorBlackSuccess:(NSNotification *)notification{
    
    NSString *user_id=notification.userInfo[@"flowers_ID"];
    NSLog(@"成功:%@",user_id);
    self.isFirstLoad=0;
    int i=0;
    int ii=0;//获取到在第几个
    for (PUModel *model in self.dizhiData) {
        i++;
        if ([[NSString stringWithFormat:@"%@",model.flowers_ID] isEqualToString:user_id]) {
            ii=i-1;
            NSLog(@"%d",ii);
            
            [self.dizhiData removeObjectAtIndex:ii];
            [self.tableView deleteRow:ii inSection:0 withRowAnimation:NO];
           
            if (self.dizhiData.count==0) {
                [self.tableView.mj_header beginRefreshing];
            }
            break;
        }
    }
}
-(void)updataData{
    [self loadData];
}
-(void)is_praiseSuccess:(NSNotification *)notification{
    
    NSString *is_praise=notification.userInfo[@"is_praise"];
    NSString *ID=notification.userInfo[@"ID"];
    int i=0;
    int ii=0;//获取到在第几个
    for (PUModel *model in self.dizhiData) {
        i++;
        if ([[NSString stringWithFormat:@"%@",model.ID] isEqualToString:ID]) {
            model.is_praise=[is_praise intValue];
            ii=i-1;
            break;
        }
    }
    [self.tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

-(void)scroVC{
    self.isFirstLoad=0;
    if (self.dizhiData.count>0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PUXuanCaiCell *cell = (PUXuanCaiCell*)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.rowHeight;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dizhiData.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    PUModel *model=self.dizhiData[indexPath.row];
    static NSString *cellIdentifier1 = @"XLSeeFlowersCell";//定义一个可重用标识
    PUXuanCaiCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier1];//从重用队列里获取可重用的cell
    if (cell==nil)
    {
        //如果不存在，创建一个可重用cell
        cell =[[PUXuanCaiCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier1] ;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.backgroundColor=[UIColor clearColor];
    cell.delegate=self;
    cell.qgBtn.tag=indexPath.row;
    cell.model=model;
    [cell.qgBtn addTarget:self action:@selector(qgBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
    
}

-(void)qgBtnAction:(UIButton *)button{
    NSInteger index = button.tag;
    NSLog(@"%ld",(long)index);
    PUModel *model=self.dizhiData[index];
   
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
  

    PUModel *model=self.dizhiData[indexPath.row];
    PUXuanCaiDetailsVC *vc=[[PUXuanCaiDetailsVC alloc]init];
    vc.model=model;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - GKPageListViewDelegate
- (UIView *)listView {
    return self.view;
}

- (UIScrollView *)listScrollView {
    return self.tableView;
}

-(void)loadData{
    
//    [self loadArchiveData];
    if (self.isFirstLoad==0) {
        self.isFirstLoad=1;
        self.dizhiData= [PUModel mj_objectArrayWithKeyValuesArray:[PUData guanhuaData]];
//        self.dizhiData2=self.dizhiData;
        
        
        NSMutableArray *data=[NSMutableArray array];
        //创建一个归档文件夹
        NSArray *library = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
        NSString *strLib = [[library objectAtIndex:0] stringByAppendingPathComponent:@"archive"];
        BOOL directory = YES;
        if (![[NSFileManager defaultManager] fileExistsAtPath:strLib isDirectory:&directory])
        {
            [[NSFileManager defaultManager] createDirectoryAtPath:strLib withIntermediateDirectories:NO attributes:nil error:nil];
        }
        //归档
        NSString *entityArchive = [strLib stringByAppendingPathComponent:[NSString stringWithFormat:@"lhDataArchive%@",[Config getID]]];
    //    [NSKeyedArchiver archiveRootObject:data toFile:entityArchive];
        //数据源从归档中读出
        NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:entityArchive];
        NSMutableArray *array2=[NSMutableArray arrayWithArray:self.dizhiData];
        if (array.count>0) {
            array= [PUModel mj_objectArrayWithKeyValuesArray:array];
            NSLog(@"%@",array);
            
            for (int i=0; i<array2.count; i++) {
                PUModel *model1=array2[i];
                for (int j=0; j<array.count; j++) {
                    PUModel *model2=array[j];
                    if ([model1.ID isEqualToString:model2.ID]) {
//                        [array2 addObject:model1];
                        [array2 removeObjectAtIndex:i];
//                        break;
                    }
                }
                
            }
            self.dizhiData=[NSMutableArray arrayWithArray:array2];
        }
        
        self.dizhiData2=self.dizhiData;
        self.dataCount=self.dizhiData.count;
    }
  
    self.page=1;
    
    if ([Config getToken]==nil) {
        [self noToken];
    }else{
        [self load_get_they_info];
    }
    
//    [self addEmptyData];
}
-(void)noToken{
    
    //user_nickname
    //user_id
    //user_avatar
    //create_time
    //is_praise
    //id

    //张简学军
    //31605
    //https://ccost.hongyi.chat/common/pac_mm/male.png
    //2025-04-15 19:32:32
    //0
    //734

    //瑄仪
    //31776
    //https://ccost.hongyi.chat/pro/user/776/31776/1744792000550.jpg
    //2025-04-15 16:03:25
    //0
    //719

    //南宫和平
    //25803
    //https://ccost.hongyi.chat/common/pac_mm/male.png
    //2025-04-17 21:25:48
    //0
    //879

    //欣欣子
    //13443
    //https://ccost.hongyi.chat/pro/user/443/13443/1744457524946.jpg
    //2025-04-17 19:45:00
    //0
    //866
    
    
    
    PUCityListModel *model1=[[PUCityListModel alloc]init];
    model1.user_nickname=@"张简学军";
    model1.user_id=31605;
    model1.user_avatar=@"https://ccost.hongyi.chat/common/pac_mm/male.png";
    model1.create_time=@"2025-04-15 19:32:32";
    model1.is_praise=0;
    model1.ID=734;
    
    [self.data addObject:model1];
    
    PUCityListModel *model2=[[PUCityListModel alloc]init];
    model2.user_nickname=@"瑄仪";
    model2.user_id=31776;
    model2.user_avatar=@"https://ccost.hongyi.chat/pro/user/776/31776/1744792000550.jpg";
    model2.create_time=@"2025-04-15 16:03:25";
    model2.is_praise=0;
    model2.ID=719;
    
    [self.data addObject:model2];
    
    PUCityListModel *model3=[[PUCityListModel alloc]init];
    model3.user_nickname=@"南宫和平";
    model3.user_id=25803;
    model3.user_avatar=@"https://ccost.hongyi.chat/pro/user/443/13443/1744457524946.jpg";
    model3.create_time=@"2025-04-17 21:25:48";
    model3.is_praise=0;
    model3.ID=879;
    
    [self.data addObject:model3];
    
    
    PUCityListModel *model4=[[PUCityListModel alloc]init];
    model4.user_nickname=@"欣欣子";
    model4.user_id=31605;
    model4.user_avatar=@"https://ccost.hongyi.chat/common/pac_mm/male.png";
    model4.create_time=@"2025-04-17 19:45:00";
    model4.is_praise=0;
    model4.ID=866;
    
    [self.data addObject:model4];
    
    
    NSMutableArray *array=[NSMutableArray array];
    for (int i=0; i<self.data.count; i++) {
        if (i>=self.dizhiData.count) {
            break;
        }
        PUModel *model1=self.dizhiData[i];
        PUCityListModel *model2=self.data[i];
        model1.userid=[NSString stringWithFormat:@"%d",model2.user_id];
        model1.username=model2.user_nickname;
        model1.userimage=model2.user_avatar;
        model1.flowers_buyTime=model2.create_time;
//                model1.flowers_describe=model2.content;
        model1.is_praise=model2.is_praise;
        model1.flowers_ID=model1.ID;
        model1.ID=[NSString stringWithFormat:@"%d",model2.ID];

        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSString *lv = [userDefaults objectForKey:[NSString stringWithFormat:@"lv_%@_%d",[Config getID],model2.user_id]];
        if (lv==nil||[lv isEqualToString:@""]) {
            int random = (arc4random() % 5)+1;
            [userDefaults setObject:[NSString stringWithFormat:@"%d",random] forKey:[NSString stringWithFormat:@"lv_%@_%d",[Config getID],model2.user_id]];
            model1.random=random;
        }else{
            model1.random=[lv intValue];
        }
        [array addObject:model1];
       
    }
    self.dizhiData=array;
    if (self.data.count >0) {
        self.tableView.mj_footer.hidden = NO;
    }
    [self addEmptyData];
    
    
}
-(void)loadArchiveData{
    NSMutableArray *data=[NSMutableArray array];
    NSString *library=NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0];
    NSString *strLib = [library stringByAppendingPathComponent:@"archive"];
    BOOL directory = YES;
    if (![[NSFileManager defaultManager] fileExistsAtPath:strLib isDirectory:&directory]){
        [[NSFileManager defaultManager] createDirectoryAtPath:strLib withIntermediateDirectories:NO attributes:nil error:nil];
    }
    //从归档中读出
    NSString *arrayArchive =[strLib stringByAppendingPathComponent:[NSString stringWithFormat:@"goumaiDataArchive%@",[Config getID]]];//用首页唯一标示id创建文件名
    NSArray *categoryAry = [NSKeyedUnarchiver unarchiveObjectWithFile:arrayArchive];
    if (categoryAry&&[categoryAry count])
    {
        data=[NSMutableArray arrayWithArray:categoryAry];
        self.dizhiData= [PUModel mj_objectArrayWithKeyValuesArray:data];
    }
    else
    {
//        [self getRequest];//get请求界面
    }
}

-(void)addEmptyData{
    [self.tableView.mj_header endRefreshing];
    self.tableView.configuer.emptyType =  ( self.dizhiData.count == 0) ? DznEmptyDataTypeSuccess : DznEmptyDataTypeDefault;
//        self.tableView.configuer.emptyType =  DznEmptyDataTypeSuccess;
    [self.tableView reloadData];
}

-(void)showSVProgressHUDStr:(NSString *)str{
    if ([str isKindOfClass:[NSNull class]]||str==nil||[str isEqualToString:@""]) {
        return;
    }
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD showImage:[UIImage imageNamed:@""] status:str];
}
/**
 响应链的方法
 */
- (UIViewController *)viewController {
    for (UIView* next = [self.view superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}

-(void)load_get_they_info{
   
    NSDictionary *param =@{
                            @"page":@"1",
                            @"type":@"3",
                            @"last_id":@(0),
                           };
    NSString *path=@"/dynamic/list";
    NSString *url1 = [NSString stringWithFormat:@"%@%@",baseUrl,path];
    [[AFNetManager shareManager] postDataWithURLString:url1 path:path parameters:param success:^(NSURLResponse *operation, id successObject) {
        [SVProgressHUD dismiss];
        NSString *result=successObject[@"result"];
        NSDictionary *dic=@{};
        if ([successObject[@"result"] isKindOfClass:[NSString class]]) {
            //解密Base64编码的字符串
            NSString *decryptedString = [AES128 decryptString:result key:dataKey iv:dataIv];
            dic=[AES128 dictionaryWithJsonString:decryptedString];
            NSLog(@"json解析===%@",dic);
        }
        
        if ([successObject[@"code"] integerValue] == 200) {
            if (dic[@"last_id"]) {
                self.last_id=[dic[@"last_id"] intValue];
            }
            self.data= [PUCityListModel mj_objectArrayWithKeyValuesArray:dic[@"list"]];
            NSMutableArray *array=[NSMutableArray array];
            for (int i=0; i<self.data.count; i++) {
                if (i>=self.dizhiData.count) {
                    break;
                }
                PUModel *model1=self.dizhiData[i];
                PUCityListModel *model2=self.data[i];
                model1.userid=[NSString stringWithFormat:@"%d",model2.user_id];
                model1.username=model2.user_nickname;
                model1.userimage=model2.user_avatar;
                model1.flowers_buyTime=model2.create_time;
//                model1.flowers_describe=model2.content;
                model1.is_praise=model2.is_praise;
                model1.flowers_ID=model1.ID;
                model1.ID=[NSString stringWithFormat:@"%d",model2.ID];

                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                NSString *lv = [userDefaults objectForKey:[NSString stringWithFormat:@"lv_%@_%d",[Config getID],model2.user_id]];
                if (lv==nil||[lv isEqualToString:@""]) {
                    int random = (arc4random() % 5)+1;
                    [userDefaults setObject:[NSString stringWithFormat:@"%d",random] forKey:[NSString stringWithFormat:@"lv_%@_%d",[Config getID],model2.user_id]];
                    model1.random=random;
                }else{
                    model1.random=[lv intValue];
                }
                [array addObject:model1];
               
            }
            self.dizhiData=array;
            if (self.data.count >0) {
                self.tableView.mj_footer.hidden = NO;
            }
            if (self.dizhiData.count==self.dataCount) {
                self.tableView.mj_footer.hidden = YES;
            }
        } else {
            [self showSVProgressHUDStr:successObject[@"message"]];
        }
       
        [self addEmptyData];
    } failure:^(NSError *error) {
        NSLog(@"错误：%@",error);
//        if (self.loveLateAppDynamicModel.data.count == 0) {
//            self.loveLateAppTableView.mj_footer.hidden = YES;
//        }
        [self addEmptyData];
    }];
}
-(void)loadMore_get_they_info{
  
    NSDictionary *param =@{
                            @"page":[NSString stringWithFormat:@"%d",(int)++self.page],
                            @"type":@"3",
                            @"last_id":@(self.last_id),
                           };
    NSString *path=@"/dynamic/list";
    NSString *url1 = [NSString stringWithFormat:@"%@%@",baseUrl,path];
    [[AFNetManager shareManager] postDataWithURLString:url1 path:path parameters:param success:^(NSURLResponse *operation, id successObject) {
        
        NSString *result=successObject[@"result"];
        NSDictionary *dic=@{};
        if ([successObject[@"result"] isKindOfClass:[NSString class]]) {
            //解密Base64编码的字符串
            NSString *decryptedString = [AES128 decryptString:result key:dataKey iv:dataIv];
            dic=[AES128 dictionaryWithJsonString:decryptedString];
            NSLog(@"json解析===%@",dic);
        }
        
        if ([successObject[@"code"] integerValue] == 200) {
            if (dic[@"last_id"]) {
                self.last_id=[dic[@"last_id"] intValue];
            }
            NSArray *array = [PUCityListModel mj_objectArrayWithKeyValuesArray:dic[@"list"]];
            [self.data addObjectsFromArray:array];
            
            NSMutableArray *array2=[NSMutableArray array];
            for (int i=0; i<self.data.count; i++) {
                if (i>=self.dizhiData2.count) {
                    break;
                }
                PUModel *model1=self.dizhiData2[i];
                PUCityListModel *model2=self.data[i];
                model1.userid=[NSString stringWithFormat:@"%d",model2.user_id];
                model1.username=model2.user_nickname;
                model1.userimage=model2.user_avatar;
                model1.flowers_buyTime=model2.create_time;
//                model1.flowers_describe=model2.content;
                model1.is_praise=model2.is_praise;
                model1.flowers_ID=model1.ID;
                model1.ID=[NSString stringWithFormat:@"%d",model2.ID];
               
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                NSString *lv = [userDefaults objectForKey:[NSString stringWithFormat:@"lv_%@_%d",[Config getID],model2.user_id]];
                if (lv==nil||[lv isEqualToString:@""]) {
                    int random = (arc4random() % 5)+1;
                    [userDefaults setObject:[NSString stringWithFormat:@"%d",random] forKey:[NSString stringWithFormat:@"lv_%@_%d",[Config getID],model2.user_id]];
                    model1.random=random;
                }else{
                    model1.random=[lv intValue];
                }
                
                [array2 addObject:model1];

            }
            self.dizhiData=array2;
            if (array.count == 0) {
                self.tableView.mj_footer.hidden = YES;
            }
            if (self.dizhiData.count==self.dataCount) {
                self.tableView.mj_footer.hidden = YES;
            }
        } else {
            [self showSVProgressHUDStr:successObject[@"message"]];
        }
        [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"错误：%@",error);
        [self.tableView.mj_footer endRefreshing];
    }];
    
}
@end
